package com.letoy.edu.utils;

import com.letoy.edu.dao.UserApiMapper;
import com.letoy.edu.entity.MyApi;
import com.letoy.edu.entity.User;

import com.letoy.edu.service.UserApiService;
import com.letoy.edu.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class DynamicPermission {

    @Resource
    UserService userService;

    @Resource
    UserApiService userApiService;

    /**
     * 判断有访问API的权限
     *
     * @param request
     * @param authentication
     * @return
     */
    public boolean checkPermission(HttpServletRequest request,
                                   Authentication authentication) {

        Object principal = authentication.getPrincipal();
        System.out.println(authentication);
        System.out.println("DynamicPermission principal = " + principal);
        System.out.println(principal.toString());
        if (principal instanceof UserDetails) {

            UserDetails userDetails = (UserDetails) principal;
            //得到当前的账号
            String username = userDetails.getUsername();
            //Collection<? extends GrantedAuthority> roles = userDetails.getAuthorities();

            System.out.println("DynamicPermission  username = " + username);

            String id = userService.getUserIdByNamePassword(userDetails.getUsername(), userDetails.getPassword());
            System.out.println("user id:" + id);
            List<MyApi> myApiList = userApiService.getMyApiListByUserId(id);

            AntPathMatcher antPathMatcher = new AntPathMatcher();
            //当前访问路径
            String requestURI = request.getRequestURI();
            //提交类型
            String urlMethod = request.getMethod();

            System.out.println("DynamicPermission requestURI = " + requestURI);
            boolean rs = myApiList.stream().anyMatch(item -> {
                boolean hashAntPath = antPathMatcher.match(item.getUrl(), requestURI);

                //判断请求方式是否和数据库中匹配（数据库存储：GET,POST,PUT,DELETE）
                String dbMethod = item.getMethod();

                //处理null，万一数据库存值
                dbMethod = (dbMethod == null) ? "" : dbMethod;
                int hasMethod = dbMethod.indexOf(urlMethod);

                //两者都成立，返回真，否则返回假
                return hashAntPath && (hasMethod != -1);
            });
            System.out.println("是否在权限中：" + rs);
            return rs;

        } else {
            System.out.println("不是UserDetails类型！");
            return false;

        }

    }
}

























